class Chat {
	constructor(arg) {
		this.chat = {
			timedTask: null, // 定时任务
			socket: null,
			// 是否已连接
			connected: function() {
				return chat.socket != null &&
					chat.socket != undefined &&
					chat.socket.readyState == WebSocket.OPEN;
			},
			getFriendList: function() {
				var localFriendList = app.getFriendList();
				if (localFriendList != null && localFriendList.length > 0) {
					return;
				}
				var user = app.getUserGlobalInfo();
				mui.ajax(app.serverUrl + "/friend/list", {
					data: {
						userId: user.id
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'get', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						if (res.code == 0) {
							var friendList = res.data;
							app.setFriendList(friendList);
						}
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						app.showToast(type, "error");
					}
				});
			},
			getUnreadMessageList: function() {
				var user = app.getUserGlobalInfo();
				var url = app.serverUrl + "/message/unread";
				console.log("app.getIsDownloadHistory(user.id) ==> " + app.getIsDownloadHistory(user.id));
				if(app.getIsDownloadHistory(user.id) != "true"){
					url = app.serverUrl + "/message/all";
				}
				mui.ajax(url, {
					data: {
						userId: user.id
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'get', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						if (res.code == 0) {
							var unreadMessageList = res.data;
							if (!unreadMessageList) {
								return;
							}
							// 保存聊天记录到本地
							app.saveChatHistory(unreadMessageList, user.id);
							// 保存聊天快照到本地
							app.saveChatSnapshot(unreadMessageList, user.id);
							// 设置已经加载过历史聊天记录
							app.setIsDownloadHistory(user.id)
							// 对这些未签收的消息，批量签收
							var msgIds = "";
							for (var i = 0; i < unreadMessageList.length; i++) {
								var unreadMessage = unreadMessageList[i];
								// 拼接批量接受的消息id字符串，逗号间隔
								var messageList = unreadMessage.messageList;
								for (var j = 0; j < messageList.length; j++) {
									var message = messageList[j];
									msgIds += message.id + ",";
								}
							}
							console.log(msgIds);
							// 调用批量签收的方法
							chat.signMsgList(msgIds, user.id);
						}
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						app.showToast(type, "error");
					}
				});
			},
			init: function() {
				if (window.WebSocket) {
					// 如果当前的状态已经连接，那就不需要重复初始化websocket
					console.log("是否已经连接：" + chat.connected());
					if (chat.connected()) {
						return false;
					}
					console.log("是否已经连接：" + chat.connected());
					// 创建websocket连接
					chat.socket = new WebSocket(app.chatServerUrl);
					chat.socket.onopen = chat.wsopen;
					chat.socket.onclose = chat.wsclose;
					chat.socket.onerror = chat.wserror;
					chat.socket.onmessage = chat.wsmessage;
					chat.getFriendList();
					chat.getUnreadMessageList();
				} else {
					alert("手机设备过旧，请升级手机设备...");
				}
			},
			// 发送信息
			sendMessage: function(data) {
				// 如果当前websocket的状态是已打开，则直接发送， 否则重连
				if (chat.connected()) {
					chat.socket.send(data);
				} else {
					chat.init(); // 重连websocket
				}
			},
			// 重新发送消息
			resendMessage: function(data) {
				console.log("重新发送消息...");
				chat.sendMessage(data);
			},
			wsopen: function() {
				console.log("websocket连接已建立...");

				var user = app.getUserGlobalInfo();
				// 构建messageData
				var messageData = {
					header: {
						messageType: app.CONNECT,
						sendUserId: user.id,
						receiveUserId: null
					},
					body: {
						message: null
					},
					extension: {}
				};
				// 发送消息
				chat.sendMessage(JSON.stringify(messageData));
				// 定时发送心跳
				if (!chat.timedTask) {
					chat.timedTask = setInterval(chat.keepalive, 10000);
				}
			},
			wsmessage: function(res) {
				var user = app.getUserGlobalInfo();
				console.log("接受到消息：" + res.data);
				// 转换DataContent为对象
				var dataContent = JSON.parse(res.data);
				var messageType = dataContent.header.messageType;
				if (messageType == app.PULL_FRIEND) {
					getFriendList();
					return false;
				}

				// 如果不是重新拉取好友列表，则获取聊天消息模型，渲染接收到的聊天记录
				var message = dataContent.body.message;
				var sendUserId = dataContent.header.sendUserId;
				var receiveUserId = dataContent.header.receiveUserId;
				var messageId = dataContent.body.messageId;

				// 调用聊天webview的receiveMsg方法
				var chatingWebview = plus.webview.getWebviewById("chatting-" + sendUserId);
				var isRead = true; // 设置消息的默认状态为已读
				if (chatingWebview != null) {
					chatingWebview.evalJS("receiveMsg('" + message + "')");
					chatingWebview.evalJS("resizeScreen()");
					// 接受到消息之后，对消息记录进行签收
					chat.signMsgList(messageId + ",", user.id);
				} else {
					isRead = false; // thisWebview 聊天页面没有打开，标记消息未读状态
				}

				var chatHistory = {
					ownerId: user.id,
					otherId: sendUserId,
					message: message,
					messageId: messageId,
					type: 2
				}
				// 保存聊天历史记录到本地缓存
				app.saveOneChatHistory(chatHistory);
				// 保存聊天快照记录到本地缓存
				var snapshotMessage = {
					ownerId: user.id,
					otherId: sendUserId,
					message: message,
					messageId: messageId,
					type: 2,
					isRead: false
				}
				app.saveOneChatSnapshot(snapshotMessage, user.id);
				// 加载聊天快照列表
				var chatWebview = plus.webview.getWebviewById("chat.html");
				if(chatWebview != null){
					chatWebview.evalJS("loadingChatSnapshot()");
				}
			},
			wsclose: function() {
				console.log("连接关闭...");
			},
			wserror: function() {
				console.log("发生错误...");
			},
			signMsgList: function(msgIds, userId) {
				if (!msgIds) {
					return;
				}
				var msgIdArr = msgIds.split(",");
				// 构建批量签收对象的模型
				var messageData = {
					header: {
						messageType: app.SIGNED,
						signUserId: userId
					},
					extension: {
						messageIdArr: msgIdArr
					}
				};
				// 发送批量签收的请求
				chat.sendMessage(JSON.stringify(messageData));
			},
			keepalive: function() {
				// 构建messageData
				var messageData = {
					header: {
						messageType: app.KEEPALIVE
					}
				};
				// 发送心跳
				chat.sendMessage(JSON.stringify(messageData));
			}
		};
	}
}
